package spreadsheet.ui;

import java.awt.Component;
import javax.swing.DefaultCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;
import spreadsheet.SpreadSheetCell;

/**
 * Class for showing calculated values for formulas and for ensuring a SpreadSheetCell object in every cell
 * even when the user types the number directly in the cell.
 */
public class SpreadSheetCellEditor extends DefaultCellEditor {
    
    private int row, col;
    private Table tbl;
    
    /**
     * Constructor for SpreadSheetCellEditor
     */
    public SpreadSheetCellEditor() {
        super( new JTextField() );
    }
    
    @Override
    public Component getTableCellEditorComponent( JTable table, Object value, boolean isSelected, int row, int column ) {
        this.row = row;
        this.col = column;
        JTextField txt = ( JTextField )getComponent();
        Object obj = table.getValueAt( row, column );
        txt.setText( obj == null ? "" : ((SpreadSheetCell) obj).toFormulaString() );
        tbl = ( Table )table;
        return txt;        
    }
    
    @Override
    public Object getCellEditorValue() {
        Object obj = super.getCellEditorValue();
        if( !( obj instanceof SpreadSheetCell ) ) {
            String strType = SpreadSheetCell.CELL_TYPES_FORMULA;//by default it is formula
            try {
                Double.parseDouble( obj.toString() );//if we can parse the number then it is primitive
                strType = SpreadSheetCell.CELL_TYPES_PRIMITIVE;
            } catch( Exception e ) {}
            obj = new SpreadSheetCell( strType, obj.toString() );
        }
        return obj;
    }
    
    @Override
    public boolean stopCellEditing() {
        boolean b = super.stopCellEditing();
        tbl.getSpreadSheet().setCell( ( SpreadSheetCell )tbl.getValueAt(row, col), row, col );
        return b;
    }
}